<?php

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

$exc = new exchange($ecs->table('warehouse'), $db, 'w_id', 'w_name');

if ($_REQUEST['act'] == 'getStore')
{
    include(ROOT_PATH.'includes/cls_json.php');
    $json   = new JSON;

	$id_dist = !empty($_REQUEST['id_dist']) ? intval($_REQUEST['id_dist']) : 0;
	
	if($id_dist){
		$sql = "SELECT id,name FROM" . $ecs->table('store') . " WHERE id_dist = '$id_dist'";
		$res['store'] = $db->getAll($sql);
	}
	die($json->encode($res));
}
/*------------------------------------------------------ */
//-- 仓库列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
    $smarty->assign('ur_here',      $_LANG['warehouse_list']);
    $smarty->assign('action_link',  array('text' => $_LANG['add_warehouse'], 'href' => 'rg_warehouse.php?act=add'));
    $smarty->assign('full_page',    1);

    $warehouse_list = get_warehouselist();
    $smarty->assign('warehouse_list',  $warehouse_list['warehouse']);
    $smarty->assign('filter',       $warehouse_list['filter']);
    $smarty->assign('record_count', $warehouse_list['record_count']);
    $smarty->assign('page_count',   $warehouse_list['page_count']);

    /* 排序标记 */
    $sort_flag  = sort_flag($warehouse_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    $smarty->display('rg_warehouse_list.htm');
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $warehouse_list = get_warehouselist();
    $smarty->assign('warehouse_list',  $warehouse_list['warehouse']);
    $smarty->assign('filter',       $warehouse_list['filter']);
    $smarty->assign('record_count', $warehouse_list['record_count']);
    $smarty->assign('page_count',   $warehouse_list['page_count']);

    /* 排序标记 */
    $sort_flag  = sort_flag($warehouse_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('rg_warehouse_list.htm'), '',
        array('filter' => $warehouse_list['filter'], 'page_count' => $warehouse_list['page_count']));
}

/*------------------------------------------------------ */
//-- 列表页编辑名称
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_w_name')
{
    check_authz_json('warehouse_manage');

    $id     = intval($_POST['id']);
    $name   = json_str_iconv(trim($_POST['val']));

    /* 检查名称是否重复 */
    if ($exc->num("w_name", $name, $id) != 0)
    {
        make_json_error(sprintf($_LANG['w_name_exist'], $name));
    }
    else
    {
        if ($exc->edit("w_name = '$name'", $id))
        {
            admin_log($name, 'edit', 'warehouse');
            clear_cache_files();
            make_json_result(stripslashes($name));
        }
        else
        {
            make_json_result(sprintf($_LANG['warehouse_edit_fail'], $name));
        }
    }
}

/*------------------------------------------------------ */
//-- 删除仓库
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('warehouse_manage');

    $id = intval($_GET['id']);
    $name = $exc->get_name($id);
    $exc->drop($id);

    /* 更新仓库 */
    $table_array = array('store','products','order_goods','cart');
    foreach ($table_array as $value)
    {
        $sql = "UPDATE " . $ecs->table($value) . " SET w_id = 0 WHERE w_id = '$id'";
        $db->query($sql);
    }

    /* 记日志 */
    admin_log($name, 'remove', 'warehouse');

    /* 清除缓存 */
    clear_cache_files();

    $url = 'rg_warehouse.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch')
{
    /* 取得要操作的记录编号 */
    if (empty($_POST['checkboxes']))
    {
        sys_msg($_LANG['no_record_selected']);
    }
    else
    {
        /* 检查权限 */
        admin_priv('warehouse_manage');

        $ids = $_POST['checkboxes'];

        if (isset($_POST['remove']))
        {
            /* 删除记录 */
            $sql = "DELETE FROM " . $ecs->table('warehouse') . " WHERE w_id " . db_create_in($ids);
            $db->query($sql);

            /* 更新仓库 */
            $table_array = array('store','products','order_goods','cart');
            foreach ($table_array as $value){
                $sql = "UPDATE " . $ecs->table($value) . " SET w_id = 0 WHERE w_id " . db_create_in($ids) . " ";
                $db->query($sql);
            }

            /* 记日志 */
            admin_log('', 'batch_remove', 'warehouse');

            /* 清除缓存 */
            clear_cache_files();

            sys_msg($_LANG['batch_drop_ok']);
        }
    }
}

/*------------------------------------------------------ */
//-- 添加、编辑仓库
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    /* 检查权限 */
    admin_priv('warehouse_manage');

    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add';
    $smarty->assign('form_action', $is_add ? 'insert' : 'update');

    /* 初始化、取得仓库信息 */
    if ($is_add){
        $warehouse = array(
            'w_id'     => 0,
            'w_name'   => '',
            'w_desc'   => '',
            'store_list'   => array()
        );
    }else{
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }

        $id = $_GET['id'];
        $sql = "SELECT * FROM " . $ecs->table('warehouse') . " WHERE w_id = '$id'";
        $warehouse = $db->getRow($sql);
        if (empty($warehouse))
        {
            sys_msg('warehouse does not exist');
        }

        /* 关联的地区 */
        $sql = "SELECT id, name FROM " . $ecs->table('store') . " WHERE w_id = '$id'";
        $warehouse['store_list'] = $db->getAll($sql);
    }

    $smarty->assign('warehouse', $warehouse);

    /* 取得地区 */
    $country_list = get_regions();
    $smarty->assign('countries', $country_list);

    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', $_LANG['add_warehouse']);
    }
    else
    {
        $smarty->assign('ur_here', $_LANG['edit_warehouse']);
    }
    if ($is_add)
    {
        $href = 'rg_warehouse.php?act=list';
    }
    else
    {
        $href = 'rg_warehouse.php?act=list&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => $_LANG['warehouse_list']));
    assign_query_info();
    $smarty->display('rg_warehouse_info.htm');
}

/*------------------------------------------------------ */
//-- 提交添加、编辑仓库
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
    /* 检查权限 */
    admin_priv('warehouse_manage');

    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert';

    /* 提交值 */
    $warehouse = array(
        'w_id'     => intval($_POST['id']),
        'w_name'   => sub_str($_POST['w_name'], 255, false),
        'w_desc'   => $_POST['w_desc']
    );

    /* 判断名称是否重复 */
    if (!$exc->is_only('w_name', $warehouse['w_name'], $warehouse['w_id']))
    {
        sys_msg($_LANG['w_name_exist']);
    }

    /* 检查是否选择了地区 */
    if (empty($_POST['stores']))
    {
        sys_msg("没有设置店铺");
    }

    /* 保存仓库信息 */
    if ($is_add)
    {
        $db->autoExecute($ecs->table('warehouse'), $warehouse, 'INSERT');
        $warehouse['w_id'] = $db->insert_id();
    }
    else
    {
        $db->autoExecute($ecs->table('warehouse'), $warehouse, 'UPDATE', "w_id = '$warehouse[w_id]'");
    }

    /* 更新店铺表 */
    if (!$is_add)
    {
        $sql = "UPDATE " . $ecs->table('store') . " SET w_id = 0 WHERE w_id = '$warehouse[w_id]'";
        $db->query($sql);
    }

    if (isset($_POST['stores']))
    {
        $sql = "UPDATE " . $ecs->table('store') . " SET w_id = '$warehouse[w_id]' WHERE id " . db_create_in($_POST['stores']);
        $db->query($sql);
    }

    /* 记日志 */
    if ($is_add)
    {
        admin_log($warehouse['w_name'], 'add', 'warehouse');
    }
    else
    {
        admin_log($warehouse['w_name'], 'edit', 'warehouse');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    if ($is_add)
    {
        $links = array(
            array('href' => 'rg_warehouse.php?act=add', 'text' => $_LANG['continue_add_warehouse']),
            array('href' => 'rg_warehouse.php?act=list', 'text' => $_LANG['back_warehouse_list'])
        );
        sys_msg($_LANG['add_warehouse_ok'], 0, $links);
    }
    else
    {
        $links = array(
            array('href' => 'rg_warehouse.php?act=list&' . list_link_postfix(), 'text' => $_LANG['back_warehouse_list'])
        );
        sys_msg($_LANG['edit_warehouse_ok'], 0, $links);
    }
}

/**
 * 取得仓库列表
 * @return  array
 */
function get_warehouselist()
{
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'w_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        /* 查询记录总数，计算分页数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('warehouse');
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('warehouse') . " ORDER BY $filter[sort_by] $filter[sort_order]";

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
        $arr[] = $rows;
    }

    return array('warehouse' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

?>